﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// excel
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.IO;
// thread
using System.Threading;

namespace mesRUpload
{
    class CSVInfo
    {
        NoticeProgressBar npb; // 进度条
        private const int maxNum = 80000, mintimeout = 5, minNum = 30000, maxtimeout = 8;
        private int timeout = 20;

        private static CSVInfo m_instance;

        private List<string> list_paramsTitle; // 标题

        private List<string> list_cellCode; // 电芯码

        private List<string> list_virtualCode; // 虚拟码

        private List<List<string>> list_csv; // csv 数据表

        public int curRow { get; set; }
        public int success { get; set; }
        public int currentLine { get; set; }

        public static int parallelnum { get; set; }

        public static CSVInfo getinstance()
        {
            if (m_instance == null)
            {
                m_instance = new CSVInfo();
            }

            return m_instance;
        }

        public void init()
        {
            //npb = new NoticeProgressBar(false);

            list_paramsTitle = new List<string>();
            list_cellCode = new List<string>();
            list_virtualCode = new List<string>();
            list_csv = new List<List<string>>();

            parallelnum = 0;

            currentLine = CodeCollection.DATA_ISNOTEXIST;
            success = CodeCollection.EXECUTE_FAIL;
        }

        /// <summary>
        /// params 标题
        /// </summary>
        public void insertPTList(string title) { list_paramsTitle.Add(title); }
        public List<string> getPTList() { return list_paramsTitle; }

        /// <summary>
        /// 电芯码
        /// </summary>
        public void insertCcList(string cellCode) { list_cellCode.Add(cellCode); }
        public List<string> getCcList() { return list_cellCode; }

        /// <summary>
        /// 虚拟码
        /// </summary>
        public void insertVcList(string virtualCode) { list_virtualCode.Add(virtualCode); }
        public List<string> getVcList() { return list_virtualCode; }

        /// <summary>
        /// csv 列表
        /// </summary>
        public void insertCSV(List<string> data) { list_csv.Add(data); }
        public List<List<string>> getCSV() { return list_csv; }

        public string getCcInVc(string keyword)
        {
            if (list_virtualCode.Contains(keyword))
            {
                return list_cellCode[list_virtualCode.IndexOf(keyword)];
            }
            else
            {
                return "";
            }
        }

        public string getVcInCc(string keyword)
        {
            if (list_cellCode.Contains(keyword))
            {
                return list_virtualCode[list_cellCode.IndexOf(keyword)];
            }
            else
            {
                return "";
            }
        }

        public void setCurrentLine(string keyword, bool isSfc)
        {
            if (isSfc)
            {
                if (list_virtualCode != null && list_virtualCode.Count() > 0)
                {
                    currentLine = list_virtualCode.IndexOf(keyword);
                }
            }
            else
            {
                if (list_cellCode != null && list_cellCode.Count() > 0)
                {
                    currentLine = list_cellCode.IndexOf(keyword);
                }
            }
        }

        public void clear()
        {
            if (list_cellCode != null && list_cellCode.Count() > 0)
            {
                list_cellCode.Clear();
            }

            if (list_virtualCode != null && list_virtualCode.Count() > 0)
            {
                list_virtualCode.Clear();
            }

            if (list_paramsTitle != null && list_paramsTitle.Count() > 0)
            {
                list_paramsTitle.Clear();
            }

            if (list_csv != null)
            {
                for (int i = 0; i < list_csv.Count(); i++)
                {
                    list_csv[i].Clear();
                }
                list_csv.Clear();
            }

            currentLine = CodeCollection.DATA_ISNOTEXIST;
            success = CodeCollection.EXECUTE_FAIL;
        }

        public void loadFile(string filePath)
        {
            NoticeProgressBar.title = filePath + " —— 加载中......";

            MESUpload.form1.DoSearchSFC(false);

            Timing.start();

            try
            {
                clear();

                IWorkbook wk = null;
                string extension = System.IO.Path.GetExtension(filePath);
                FileStream fs = File.OpenRead(filePath);

                success = CodeCollection.EXECUTE_FAIL;

                if (extension.Equals(".xls")) // 2003 版本
                {
                    wk = new HSSFWorkbook(fs); // 把 xls 文件中的数据写入wk中
                }
                else if (extension.Equals(".xlsx")) // .xlsx 2007 版本
                {
                    wk = new XSSFWorkbook(fs); // 把 xlsx 文件中的数据写入wk中
                }
                else
                {
                    loadCSV(filePath);
                    return;
                }

                fs.Close();

                ISheet sheet = wk.GetSheetAt(0); // 读取当前表数据

                IRow row = sheet.GetRow(0); // 读取当前行数据

                if (sheet.LastRowNum > maxNum)
                {
                    timeout = mintimeout;
                    npb = new NoticeProgressBar(false); // 启动进度条
                }
                else if (sheet.LastRowNum > minNum)
                {
                    timeout = maxtimeout;
                    npb = new NoticeProgressBar(false); // 启动进度条
                }

                if (getPTList().Count == 0)
                {
                    for (int j = 3; j < sheet.GetRow(0).LastCellNum; j++)
                    {
                        insertPTList(row.GetCell(j).ToString());
                    }
                }

                if (getCcList().Count == 0 && getVcList().Count == 0 && getCSV().Count == 0)
                {
                    for (int i = 1; i < sheet.LastRowNum; i++) // LastRowNum 总行数-1
                    {
                        curRow = i + 1;

                        List<string> temp = new List<string>();
                        row = sheet.GetRow(i);  // 读取当前行数据
                        if (row != null)
                        {
                            string code1 = row.GetCell(1).ToString();
                            insertCcList(code1);

                            string code2 = row.GetCell(2).ToString();
                            insertVcList(code2);
                            if (i != 0)
                            {
                                for (int j = 3; j < row.LastCellNum; j++)
                                {
                                    string cell = row.GetCell(j).ToString();
                                    temp.Add(cell);
                                }
                                insertCSV(temp);
                            }
                        }

                        if (npb != null && curRow % (sheet.LastRowNum / 100) == 0)
                        {
                            npb.set(curRow / (sheet.LastRowNum / 100)
                                , (curRow / (sheet.LastRowNum / 100)).ToString() + "/100，加载中...");
                            Thread.Sleep(timeout);
                        }
                    }
                }

                wk.Close();
                success = CodeCollection.EXECUTE_SUCCESS;
                MESUpload.form1.DoSearchSFC(true);
            }
            catch (Exception e)
            {
                MESUpload.form1.DoSearchSFC(false, true);

                string filemessage = filePath + "," + "csv 文件加载," + Timing.startTime()
                    + "," + Timing.end() + "," + Timing.spendTime() + ",异常,"
                    + Timing.exceptionMess(e);
                MESUpload.logger.Warn(filemessage);
            }
        }

        private void loadCSV(string filePath)
        {
            Timing.start();

            StreamReader reader = null;
            FileStream fs = null;

            try
            {
                fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                reader = new StreamReader(fs, System.Text.Encoding.GetEncoding("gb2312"));

                string line = string.Empty;
                string[] values;

                int count = rowCount(filePath);
                if (count > maxNum)
                {
                    timeout = mintimeout;
                    npb = new NoticeProgressBar(false); // 启动进度条
                }
                else if (count > minNum)
                {
                    timeout = maxtimeout;
                    npb = new NoticeProgressBar(false); // 启动进度条
                }

                int first = 0;
                while ((line = reader.ReadLine()) != null)
                {
                    curRow = first + 2;

                    values = line.Split(',');
                    int linenum = values.Count();
                    if (linenum >= 3)
                    {
                        if (first > 0)
                        {
                            insertCcList(values[1]); // 电芯码
                            insertVcList(values[2]); // 虚拟码
                        }

                        List<string> temp = new List<string>();
                        for (int j = 3; j < linenum; j++)
                        {
                            if (first > 0)
                            {
                                temp.Add(values[j]); // 对应值
                            }
                            else
                            {
                                insertPTList(values[j]); // 对应标题
                            }
                        }
                        if (temp.Count > 0)
                        {
                            insertCSV(temp);
                        }

                        if (npb != null && curRow % (count / 100) == 0)
                        {
                            npb.set(curRow / (count / 100)
                                , (curRow / (count / 100)).ToString() + "/100，加载中...");
                            Thread.Sleep(timeout);
                        }
                    }

                    first++;
                }
                fs.Close();
                reader.Close();

                success = CodeCollection.EXECUTE_SUCCESS;
            }
            catch (Exception e)
            {
                MESUpload.form1.DoSearchSFC(false, true);

                string filemessage = filePath + "," + "csv 文件加载," + Timing.startTime()
                           + "," + Timing.end() + "," + Timing.spendTime() + ",异常,"
                           + Timing.exceptionMess(e);
                MESUpload.logger.Warn(filemessage);
            }
            finally
            {
                if (fs != null)
                    fs.Close();
                if (reader != null)
                    reader.Close();
            }

        }

        private int rowCount(string filePath)
        {
            StreamReader reader = null;
            FileStream fs = null;
            try
            {
                fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                reader = new StreamReader(fs, System.Text.Encoding.GetEncoding("gb2312"));
                int count = 0;
                string line0 = string.Empty;
                while ((line0 = reader.ReadLine()) != null)
                {
                    if (line0.Split(',').Count() > 3)
                    {
                        count++;
                    }
                    else
                    {
                        continue;
                    }
                }
                NoticeProgressBar.Count = count;
                fs.Close();
                reader.Close();

                return count;
            }
            finally
            {
                if (fs != null)
                    fs.Close();
                if (reader != null)
                    reader.Close();
            }
        }

        private void setupProgressBar(string filePath)
        {
            if (parallelnum == 0)
            {
                rowCount(filePath);

                NoticeProgressBar.show_circle_dialog();

                parallelnum++;
            }
        }

        private void shutdownProgressBar()
        {
            parallelnum = 0;

            MESUpload.form1.DoSearchSFC(true);

            NoticeProgressBar.close_circle_dialog();
        }

    }
}
